<template>
    <div class="wh-100%">
        <div v-if="daily.length === 0" class="flex-center wh-100%">
            <n-result
                status="418"
                title="暂无数据"
                description="一切尽在不言中"
            >
            </n-result>
        </div>
        <div v-else class="flex flex-col gap-2.5">
            <n-card title="今日天气">
                <n-data-table
                    :data="daily"
                    :columns="dailyWeatherColumns"
                    :scroll-x="1500"
                    max-height="500"
                ></n-data-table>
            </n-card>
            <n-card title="未来30日天气">
                <n-data-table
                    :data="monthly"
                    :columns="monthlyWeatherColumns"
                    :scroll-x="1500"
                    max-height="500"
                ></n-data-table>
            </n-card>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import type {
    DailyWeatherPrediction,
    MonthlyWeatherPrediction,
} from "@/types/prediction.ts";

import {
    monthlyWeatherColumns,
    dailyWeatherColumns,
} from "@/utils/table-column";

import { getWeatherPrediction } from "@/service/api/predict";

const props = defineProps<{
    timestamp: number;
}>();

const dailyData = new Map<number, DailyWeatherPrediction[]>();
const monthlyData = new Map<number, MonthlyWeatherPrediction[]>();

const daily = ref<DailyWeatherPrediction[]>([]);
const monthly = ref<MonthlyWeatherPrediction[]>([]);

const handleQuery = async () => {
    try {
        const res = await getWeatherPrediction(props.timestamp);
        const data = res.data as {
            daily: DailyWeatherPrediction[];
            monthly: MonthlyWeatherPrediction[];
        };
        dailyData.set(props.timestamp, data.daily);
        monthlyData.set(props.timestamp, data.monthly);

        daily.value = data.daily;
        monthly.value = data.monthly;
    } catch (err) {
        dailyData.set(props.timestamp, []);
        monthlyData.set(props.timestamp, []);

        daily.value = [];
        monthly.value = [];

        window.NMessage.error((err as Error).message);
    }
};

watch(
    () => props.timestamp,
    async (timestamp) => {
        if (dailyData.has(timestamp)) {
            daily.value = dailyData.get(timestamp) as DailyWeatherPrediction[];
            monthly.value = monthlyData.get(
                timestamp
            ) as MonthlyWeatherPrediction[];
        } else {
            await handleQuery();
        }
    }
);

onMounted(async () => {
    await handleQuery();
});

const getCurrentData = () => {
    if (daily.value.length === 0 && monthly.value.length === 0) {
        return null;
    }
    return {
        daily: daily.value,
        monthly: monthly.value,
    };
};

const handleReload = async () => {
    await handleQuery();
};

defineExpose({
    getCurrentData,
    handleReload,
});
</script>

<style scoped></style>
